/**
 * @Author: wangtao
 * @Date: 2020-06-28 15:43:56
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-20 11:49:43
 * @Description: 发布货源
 */

import React, { Component } from 'react';
import {
  BackHandler,
  DeviceEventEmitter,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  TouchableOpacity,
  View,
  SafeAreaView,
  Platform,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import {
  fontColorCoffee,
  fontColorDeepGray,
  fontColorSecDeepGray,
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorDeepRed,
  px2dp,
  splitLineColorLightGray,
  isAndroid,
} from '../../../../common/styles';
import {
  Button,
  Check,
  FormSelect,
  msg,
  cache,
  Header,
  BackImage,
} from '../../../../common';
import SourceInfo from './components/source-info-new';
import CarNeed from './components/car-need-new';
import SourceRemark from './components/source-remark-new';
import HopeFreight from './components/hope-freight-new';
import SourceAddressItem from './components/source-address-item';
import SourceContact from './components/source-contact';
import {
  allGoods,
  createGoodsSource,
  fetchUnitList,
  findBySourceId,
  updateGoodsSource,
} from '../../../../api/source-release';
import Picker from '../../../../common/picker';

const { Submit } = Button;

export default class ReleaseSource extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitleStyle: {
      alignSelf: 'center',
      textAlign: 'center',
      flex: 1,
    },
    headerRight: (
      <TouchableOpacity style={{ padding: px2dp(20) }} onPress={() => {}}>
        <Text
          allowFontScaling={false}
          style={{
            fontSize: px2dp(32),
            color: fontColorCoffee,
          }}
        />
      </TouchableOpacity>
    ),
  });

  constructor(props) {
    super(props);
    this.state = {
      currentDate: this._getCurrentDate(),
      chooseDateStr: '',
      chooseDate: '',
      chooseStartHour: '',
      chooseEndHour: '',
      sourceType: 'add', // 货源类型  add 新增  edit 编辑 resend重发
      sourceInfoIsShow: false, // 货物信息模态框显示隐藏
      sourceInfoType: 'add', // 货物信息，添加编辑
      installAddressList: [{}], // 装货地址列表
      installAddressListMaxNum: 2, // 装货地址列表最大数量
      offAddressList: [{}], // 卸地址列表
      offAddressListMaxNum: 2, // 卸货地址列表最大数量
      currentType: 1, // 当前点击的类型 1装 2卸
      currentSort: 0, // 当前点击的顺序
      supply: {
        id: null,
        // 货物信息
        supplyName: null,
        supplyTypeOneId: null,
        supplyTypeOneName: null,
        supplyTypeTwoId: null,
        supplyTypeTwoName: null,
        packagingType: null,
        packagingTypeId: null,
        isLimitDate: null,
        invalidTimeStartStr: null,
        invalidTimeEndStr: null,
        isLimitWeight: null,
        weight: null,
        weightUnit: null,
        // 用车需求
        transportationType: null,
        truckTypeList: [],
        truckLengthList: [],
        carNeedName: null,
        // 期望运费
        freightConsignorPer: null,
        freightUnit: null,
        lossesAmount: null,
        lossesUnit: null,
        messageCost: null,
        isTax: 1, // 是否含税
        // 备注
        remark: null,
      }, // 货源基本信息,此处与接口保持一致格式
      carNeedIsShow: false,
      sourceRemarkIsShow: false,
      hopeFreightIsShow: false,
      sourceContactIsShow: false,
      treeList: [], // 分类
      needReceipt: 1, // 是否需要回单 1需要 2不需要
      isWeighing: 1, // 是否需要过磅 1需要 2不需要
      isAgree: true, // 是否同意协议
      isDisabled: false,
      pickerState: false,
      unitList: [],
    };
  }

  componentDidMount() {
    this.init();
    // 处理安卓物理返回键
    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
    this.PickerState = DeviceEventEmitter.addListener('PickerState', (e) => {
      // console.log('🚀🚀🚀wimi======>>>e',e)
      this.setState({ pickerState: e });
    });
    this.loadSaveInputParams();
  }

  componentWillUnmount() {
    msg.off('selectAddress');
    Picker.hide();
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
    this.PickerState.remove();
  }

  render() {
    const {
      installAddressList,
      installAddressListMaxNum,
      offAddressList,
      offAddressListMaxNum,
      sourceInfoIsShow,
      sourceInfoType,
      carNeedIsShow,
      sourceRemarkIsShow,
      hopeFreightIsShow,
      sourceContactIsShow,
      supply,
      treeList,
      currentType,
      currentSort,
      needReceipt,
      isAgree,
      isDisabled,
      isWeighing,
    } = this.state;
    const {
      supplyName,
      packagingType,
      weight,
      weightUnit,
      isLimitWeight,
      carNeedName,
      remark,
      freightConsignorPer,
      freightUnit,
      lossesAmount,
      lossesUnit,
      messageCost,
    } = supply;

    return (
      <SafeAreaView style={{ flex: 1 }}>
        <Header
          title='发布货源'
          renderLeft={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={isAndroid ? { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                  { paddingVertical: px2dp(14), paddingRight: px2dp(40) }}
                // style={styles.leftContainer}
                onPress={() => {
                  this.backShowAlertView();
                }}
              >
                <BackImage />
              </TouchableOpacity>
            );
          }}
        />

        <ScrollView
          showsVerticalScrollIndicator={false}
          style={{ backgroundColor: mainBgColorLightGray }}
        >
          <View style={styles.container}>
            <View style={styles.addressWrap}>
              {/* 发货点 */}
              {installAddressList.map((installAddress, index) => {
                return (
                  <SourceAddressItem
                    type={1}
                    sort={index}
                    address={installAddress}
                    addressList={installAddressList}
                    addressListMaxNum={installAddressListMaxNum}
                    addAddress={this.addAddress}
                    deleteAddress={this.deleteAddress}
                    choosePutTime={this.choosePutTime}
                    onChangeContactModal={this.onChangeContactModal}
                  />
                );
              })}
              {/* 卸货点 */}
              {offAddressList.map((offAddress, index) => {
                return (
                  <SourceAddressItem
                    type={2}
                    sort={index}
                    address={offAddress}
                    addressList={offAddressList}
                    addressListMaxNum={offAddressListMaxNum}
                    addAddress={this.addAddress}
                    deleteAddress={this.deleteAddress}
                    choosePutTime={this.choosePutTime}
                    onChangeContactModal={this.onChangeContactModal}
                  />
                );
              })}
            </View>
            <View style={styles.floorWrap}>
              <FormSelect
                label={
                  <>
                    <Text style={{ color: fontColorDeepRed }}>*</Text>
                    <Text style={{ color: fontColorDeepGray }}>货物信息</Text>
                  </>
                }
                labelWidth={styles.labelWidth}
                textStyles={styles.textDir}
                placeholder='必填，请输入货物信息'
                selected={{
                  value: supplyName
                    ? `${supplyName},${
                      packagingType ? `${packagingType},` : ''
                    }${weight || ''}${
                      weightUnit && isLimitWeight == 1 ? weightUnit : ''
                    }`
                    : null,
                }}
                onPress={() => {
                  this.onChangeModal({ type: 'sourceInfoIsShow', val: true });
                }}
              />
              <FormSelect
                label={
                  <>
                    <Text style={{ color: fontColorDeepRed }}>*</Text>
                    <Text style={{ color: fontColorDeepGray }}>用车需求</Text>
                  </>
                }
                labelWidth={styles.labelWidth}
                textStyles={styles.textDir}
                placeholder='必填，请输入用车需求'
                selected={{
                  value: carNeedName,
                }}
                onPress={() => {
                  this.onChangeModal({ type: 'carNeedIsShow', val: true });
                }}
              />
              <FormSelect
                label={
                  <>
                    <Text style={{ color: fontColorDeepRed }}>*</Text>
                    <Text style={{ color: fontColorDeepGray }}>期望运费</Text>
                  </>
                }
                labelWidth={styles.labelWidth}
                textStyles={styles.textDir}
                placeholder='必填，请输入运费'
                selected={{
                  value: (() => {
                    let str = '';
                    if (freightConsignorPer && freightUnit) { str += `${freightConsignorPer}元/${freightUnit}`; }
                    if (messageCost) str += `,${messageCost}元`;
                    if (lossesAmount && lossesUnit) { str += `,${lossesAmount}元/${lossesUnit}`; }
                    return str;
                  })(),
                }}
                onPress={() => {
                  this.onChangeModal({ type: 'hopeFreightIsShow', val: true });
                }}
              />
            </View>

            <View style={[styles.floorWrap]}>
              <FormSelect
                label={
                  <>
                    <Text style={{ color: fontColorDeepGray }}>备注</Text>
                  </>
                }
                labelWidth={styles.labelWidth}
                textStyles={styles.textDir}
                placeholder='选填，请输入备注'
                selected={{ value: remark }}
                onPress={() => {
                  this.onChangeModal({ type: 'sourceRemarkIsShow', val: true });
                }}
              />
              <View style={styles.receiptItem}>
                <Text style={styles.receiptItemLabel}>回单</Text>
                <View style={styles.receiptItemRight}>
                  <Text>是否需要上传回单</Text>
                  <Switch
                    trackColor={{
                      false: '#E6E6E5',
                      true: fontColorCoffee,
                    }} // 关闭状态时的边框颜色(iOS)或背景颜色(Android)。
                    value={needReceipt == 1}
                    onValueChange={(value) => {
                      if (!value) {
                        this.setState({ isWeighing: 2 }, () => {
                          this.saveInputParams();
                        });
                      }
                      this.setState(
                        { needReceipt: needReceipt == 1 ? 2 : 1 },
                        () => {
                          this.saveInputParams();
                        },
                      );
                    }}
                    testID='one'
                    thumbColor='#fff'
                  />
                </View>
              </View>
              {needReceipt == 1 && (
                <View
                  style={[
                    styles.receiptItem,
                    { borderBottomWidth: px2dp(1), borderBottomColor: '#F0EFEF' },
                  ]}
                >
                  <Text style={styles.receiptItemLabel}>过磅</Text>
                  <View style={styles.receiptItemRight}>
                    <Text>是否需要过磅</Text>
                    <Switch
                      trackColor={{
                        false: '#E6E6E5',
                        true: fontColorCoffee,
                      }}
                      value={isWeighing === 1}
                      onValueChange={(value) => {
                        this.setState({ isWeighing: value ? 1 : 2 }, () => {
                          this.saveInputParams();
                        });
                      }}
                      testID='one'
                      thumbColor='#fff'
                    />
                  </View>
                </View>
              )}
            </View>

            <View
              style={{
                width: '100%',
                flexDirection: 'row',
                marginTop: px2dp(24),
              }}
            >
              <Check
                checked={isAgree}
                onCheck={() => {
                  this.setState({ isAgree: !isAgree });
                }}
              />
              <Text style={{ fontSize: px2dp(24), marginLeft: 4 }}>
                我已阅读并同意
              </Text>
              <TouchableOpacity
                activeOpacity={0.5}
                onPress={this.jumpAgreement}
              >
                <Text style={{ color: fontColorCoffee, fontSize: px2dp(24) }}>
                  《货物运输协议》
                </Text>
              </TouchableOpacity>
            </View>

            <Submit
              text='发货'
              boxStyle={{
                width: px2dp(640),
                height: px2dp(96),
                borderRadius: px2dp(12),
                marginVertical: px2dp(100),
                overflow: 'hidden',
              }}
              btnTextStyle={{
                fontSize: px2dp(36),
              }}
              onClick={() => {
                this.confirm();
              }}
              disabled={isDisabled}
            />

            {sourceInfoIsShow && (
              <SourceInfo
                onChangeModal={(obj) => this.onChangeModal(obj)}
                onChangeVal={(obj) => this.onChangeVal(obj)}
                supply={supply}
                sourceInfoType={sourceInfoType}
                treeList={treeList}
              />
            )}
            {carNeedIsShow && (
              <CarNeed
                onChangeModal={(obj) => this.onChangeModal(obj)}
                onChangeVal={(obj) => this.onChangeVal(obj)}
                supply={supply}
              />
            )}
            {sourceRemarkIsShow && (
              <SourceRemark
                onChangeModal={(obj) => this.onChangeModal(obj)}
                onChangeVal={(obj) => this.onChangeVal(obj)}
                supply={supply}
              />
            )}
            {hopeFreightIsShow && (
              <HopeFreight
                onChangeModal={(obj) => this.onChangeModal(obj)}
                onChangeVal={(obj) => this.onChangeVal(obj)}
                supply={supply}
              />
            )}
            {sourceContactIsShow && (
              <SourceContact
                onChangeModal={(obj) => this.onChangeModal(obj)}
                onChangeContact={this.onChangeContact}
                linkType={currentType}
                linkMan={
                  currentType == 1
                    ? installAddressList[currentSort].linkMan
                    : offAddressList[currentSort].linkMan
                }
                linkMobile={
                  currentType == 1
                    ? installAddressList[currentSort].linkMobile
                    : offAddressList[currentSort].linkMobile
                }
                supply={supply}
              />
            )}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  onBackAndroid = () => {
    this.setState({
      sourceContactIsShow: false,
      hopeFreightIsShow: false,
      sourceRemarkIsShow: false,
      carNeedIsShow: false,
      sourceInfoIsShow: false,
    });
    Picker.hide();
    this.backShowAlertView();
    return true;
  };

  // 返回弹窗
  backShowAlertView = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const routerParams = state.params || {};
    const { type } = routerParams;
    if (type == 'edit' || type == 'resend') {
      msg.emit('router: back');
      return;
    }
    AsyncStorage.getItem(cache.REALSE_SOURCE)
      .then((dataJson) => {
        let data = JSON.parse(dataJson);
        if (data) {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '温馨提示',
            text: '是否保留已输入内容',
            okText: '保留',
            cancelText: '清除',
            okFn: () => {
              msg.emit('router: back');
            },
            cancelFn: () => {
              // storage.remove({
              //   key: cache.REALSE_SOURCE,
              // });
              AsyncStorage.removeItem(cache.REALSE_SOURCE, (err) => {
                console.log('清除当前企业缓存异常：', err);
              });
              msg.emit('router: back');
            },
          });
        } else {
          msg.emit('router: back');
        }
      })
      .catch((err) => {
        console.log(err);
        msg.emit('router: back');
      });
  };

  // 添加地址
  addAddress = ({ type }) => {
    let { installAddressList, offAddressList } = this.state;
    if (type === 1) {
      installAddressList.push({});
      this.setState({ installAddressList }, () => {
        this.saveInputParams();
      });
    }
    if (type === 2) {
      offAddressList.push({});
      this.setState({ offAddressList }, () => {
        this.saveInputParams();
      });
    }
  };

  // 删除地址
  deleteAddress = ({ type, sort }) => {
    let { installAddressList, offAddressList } = this.state;
    if (type === 1) {
      installAddressList.splice(sort, 1);
      this.setState({ installAddressList }, () => {
        this.saveInputParams();
      });
    }
    if (type === 2) {
      offAddressList.splice(sort, 1);
      this.setState({ offAddressList }, () => {
        this.saveInputParams();
      });
    }
  };

  // 对选择地址后进行操作
  onChangeAddress = ({
    province,
    city,
    district,
    addressDetails,
    lgt,
    lat,
    type,
    sort,
  }) => {
    let { installAddressList, offAddressList } = this.state;
    console.log(
      '🚀🚀🚀wimi======>>>  province,city,district,addressDetails,lgt,lat,type,sort,installAddressList,offAddressList',
      province,
      city,
      district,
      addressDetails,
      lgt,
      lat,
      type,
      sort,
      installAddressList,
      offAddressList,
    );
    console.log(
      '🚀🚀🚀wimi======>>>installAddressList[sort]',
      installAddressList[sort],
    );
    console.log(
      '🚀🚀🚀wimi======>>>offAddressList[sort]',
      offAddressList[sort],
    );

    if (type === 1) {
      let installAddressListSortObj = installAddressList[sort];
      if (installAddressListSortObj) {
        installAddressList.splice(
          sort,
          1,
          Object.assign(installAddressListSortObj, {
            province,
            city,
            district,
            addressDetails,
            lgt,
            lat,
            type,
            sort,
          }),
        );
        this.setState({ installAddressList }, () => {
          this.saveInputParams();
        });
      }
    }
    if (type === 2) {
      let offAddressListSortObj = offAddressList[sort];
      if (offAddressListSortObj) {
        offAddressList.splice(
          sort,
          1,
          Object.assign(offAddressListSortObj, {
            province,
            city,
            district,
            addressDetails,
            lgt,
            lat,
            type,
            sort,
          }),
        );
        this.setState({ offAddressList }, () => {
          this.saveInputParams();
        });
      }
    }
  };

  // 选择时间
  onChangeTime = ({ type, sort, times }) => {
    let { installAddressList } = this.state;
    if (times[0].split(':')[0] > times[1].split(':')[0]) {
      msg.emit('app:tip', { text: '开始时间应小于截止时间' });
      return;
    }

    if (type === 1) {
      installAddressList.splice(
        sort,
        1,
        Object.assign(installAddressList[sort], {
          loadingStartTime: times[0],
          loadingEndTime: times[1],
        }),
      );
      this.setState({ installAddressList }, () => {
        this.saveInputParams();
      });
    }
  };

  // 选择联系人弹框
  onChangeContactModal = ({ type, sort }) => {
    this.setState({
      sourceContactIsShow: true,
      currentType: type,
      currentSort: sort,
    });
  };

  // 选择联系人
  onChangeContact = ({ linkMan, linkMobile }) => {
    let {
      installAddressList,
      offAddressList,
      currentType,
      currentSort,
    } = this.state;
    if (currentType === 1) {
      installAddressList.splice(
        currentSort,
        1,
        Object.assign(installAddressList[currentSort], { linkMan, linkMobile }),
      );
      this.setState({ installAddressList }, () => {
        this.saveInputParams();
      });
    }
    if (currentType === 2) {
      offAddressList.splice(
        currentSort,
        1,
        Object.assign(offAddressList[currentSort], { linkMan, linkMobile }),
      );
      this.setState({ offAddressList }, () => {
        this.saveInputParams();
      });
    }
  };

  // 货物运输协议
  jumpAgreement = () => {
    msg.emit('router: goToNext', {
      routeName: 'CustAgreement',
      routerFrom: 'logiticsAgreement',
    });
  };

  init = () => {
    allGoods().then((res) => {
      if (res.success) {
        this.setState({ treeList: res.data });
      }
    });
    // 获取计量单位列表
    this.fetchUnitList();

    // 监听装货地址
    msg.on('selectAddress', (address) => {
      this.onChangeAddress(address);
    });
  };

  // 改变弹框显示隐藏,相关数据
  onChangeModal = ({ type, val }) => {
    this.setState({ [type]: val });
  };

  // 改变弹框相关数据
  onChangeVal = ({ type, val }) => {
    const value = this.state[type];
    this.setState({ [type]: Object.assign(value, val) }, () => {
      this.saveInputParams();
    });
  };

  // 发货
  confirm = () => {
    let {
      installAddressList,
      offAddressList,
      supply,
      needReceipt,
      unitList,
      isAgree,
      sourceType,
      isWeighing,
    } = this.state;
    // 递增组件sort
    offAddressList = offAddressList.map((item) => {
      item.sort += installAddressList.length;
      return item;
    });
    const {
      id,
      packagingTypeId,
      isLimitDate,
      invalidTimeStartStr,
      invalidTimeEndStr,
      isLimitWeight,
      weight,
      weightUnit,
      transportationType,
      truckTypeList,
      truckLengthList,
      freightConsignorPer,
      freightUnit,
      lossesAmount,
      lossesUnit,
      messageCost,
      supplyTypeTwoId,
      remark,
      isTax,
    } = supply;

    // 校验

    if (!installAddressList[installAddressList.length - 1].province) {
      msg.emit('app:tip', { text: '请填写装货地址' });
      return;
    }
    if (!installAddressList[installAddressList.length - 1].loadingStartTime) {
      msg.emit('app:tip', { text: '请填写装货时间' });
      return;
    }
    if (!offAddressList[offAddressList.length - 1].province) {
      msg.emit('app:tip', { text: '请填写卸货地址' });
      return;
    }
    // if (!offAddressList[offAddressList.length-1].loadingStartTime) {
    //   msg.emit('app:tip', {text: '请填写卸货时间'});
    //   return;
    // }
    if (!packagingTypeId) {
      msg.emit('app:tip', { text: '请填写货物信息' });
      return;
    }

    if (isLimitDate == 1 && (!invalidTimeStartStr || !invalidTimeEndStr)) {
      msg.emit('app:tip', { text: '请填写货物信息' });
      return;
    }

    if (!transportationType) {
      msg.emit('app:tip', { text: '请填写用车需求' });
      return;
    }

    if (!freightConsignorPer || !freightUnit) {
      msg.emit('app:tip', { text: '请填写期望运费' });
      return;
    }
    if (!isAgree) {
      msg.emit('app:tip', { text: '请同意货物运输协议' });
      return;
    }

    this.setState({ isDisabled: true });

    // TODO:查字典编码 需要优化
    let weightUnitObj = unitList.find((item) => {
      if (weightUnit === item.name) {
        return true;
      }
    });
    let freightUnitObj = unitList.find((item) => {
      if (freightUnit === item.name) {
        return true;
      }
    });
    let lossesUnitObj = unitList.find((item) => {
      if (lossesUnit === item.name) {
        return true;
      }
    });

    const params = {
      installAddressList,
      offAddressList,
      packagingTypeId,
      isLimitDate,
      invalidTimeStartStr,
      invalidTimeEndStr,
      isLimitWeight,
      weight,
      weightUnit: weightUnitObj ? weightUnitObj.code : freightUnitObj.code,
      transportationType,
      truckTypeList,
      truckLengthList,
      freightConsignorPer,
      freightUnit: freightUnitObj ? freightUnitObj.code : '',
      lossesAmount,
      lossesUnit: lossesUnitObj ? lossesUnitObj.code : '',
      messageCost,
      remark,
      needReceipt,
      // consignorType: 1,
      goodsTypeId: supplyTypeTwoId,
      isTax: isTax || 2,
      isWeighing: isWeighing || 2,
    };
    if (sourceType == 'edit') {
      params.id = id;
      updateGoodsSource(params)
        .then((res) => {
          this.setState({ isDisabled: false });
          if (res.success) {
            // 删除缓存
            AsyncStorage.removeItem(cache.REALSE_SOURCE, (err) => {
              console.log('清除当前企业缓存异常：', err);
            });
            DeviceEventEmitter.emit('UPDATE_LOGISTICS');
            msg.emit('router: goToNext', {
              routeName: 'ShipperSource',
            });
          } else {
            msg.emit('app:tip', { text: res.msg });
          }
        })
        .finally(() => {
          this.setState({ isDisabled: false });
        });
    } else {
      createGoodsSource(params)
        .then((res) => {
          // 删除缓存
          AsyncStorage.removeItem(cache.REALSE_SOURCE, (err) => {
            console.log('清除当前企业缓存异常：', err);
          });
          this.setState({ isDisabled: false });
          if (res.success) {
            DeviceEventEmitter.emit('UPDATE_LOGISTICS');
            msg.emit('router: goToNext', {
              routeName: 'ShipperSource',
            });
          } else {
            msg.emit('app:tip', { text: res.msg });
          }
        })
        .finally(() => {
          this.setState({ isDisabled: false });
        });
    }
  };

  // 获取计量单位列表
  fetchUnitList = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { type, id } = params;
    this.setState({ sourceType: type });
    fetchUnitList({}).then((res) => {
      if (res.success) {
        this.setState({ unitList: res.data }, (val) => {
          const { unitList } = this.state;
          if (type == 'edit' || type == 'resend') {
            findBySourceId(id).then((res) => {
              if (res.success) {
                const {
                  id,
                  installAddressList,
                  offAddressList,
                  goodsTypeName,
                  goodsTypeId,
                  parentGoodsTypeName,
                  goodsTypeParentId,
                  packagingTypeName,
                  packagingTypeId,
                  isLimitDate,
                  invalidTimeStartStr,
                  invalidTimeEndStr,
                  isLimitWeight,
                  weight,
                  weightUnit,
                  freightConsignorPer,
                  freightUnit,
                  lossesAmount,
                  lossesUnit,
                  messageCost,
                  remark,
                  needReceipt,
                  transportationType,
                  transportationTypeName,
                  truckTypeList,
                  truckLengthList,
                  isTax,
                  isWeighing,
                } = res.data;
                // TODO:查字典编码 需要优化
                let weightUnitObj = unitList.find((item) => {
                  if (weightUnit === item.code) {
                    return true;
                  }
                });
                let freightUnitObj = unitList.find((item) => {
                  if (freightUnit === item.code) {
                    return true;
                  }
                });
                let lossesUnitObj = unitList.find((item) => {
                  if (lossesUnit === item.code) {
                    return true;
                  }
                });

                this.setState({ sourceInfoType: 'edit' });

                let truckTypeListName = truckTypeList.map((item) => {
                  return item.name;
                });
                let truckLengthListName = truckLengthList.map((item) => {
                  return item.name;
                });
                this.setState({
                  installAddressList,
                  offAddressList,
                  supply: {
                    id,
                    supplyName: `${parentGoodsTypeName}-${goodsTypeName}`,
                    supplyTypeOneId: goodsTypeParentId,
                    supplyTypeOneName: parentGoodsTypeName,
                    supplyTypeTwoId: goodsTypeId,
                    supplyTypeTwoName: goodsTypeName,
                    packagingType: packagingTypeName,
                    packagingTypeId,
                    isLimitDate,
                    invalidTimeStartStr,
                    invalidTimeEndStr,
                    isLimitWeight,
                    weight,
                    weightUnit: weightUnitObj ? weightUnitObj.name : '',
                    freightConsignorPer,
                    freightUnit: freightUnitObj ? freightUnitObj.name : '',
                    lossesAmount,
                    lossesUnit: lossesUnitObj ? lossesUnitObj.name : '',
                    messageCost,
                    transportationType,
                    transportationTypeName,
                    truckTypeList,
                    truckLengthList,
                    carNeedName: `${transportationTypeName},${truckTypeListName},${truckLengthListName}`,
                    remark,
                    isTax: isTax || 2,
                  },
                  isWeighing: isWeighing || 2,
                  needReceipt,
                });
              }
            });
          }
        });
      }
    });
  };

  // 时间选择器
  choosePutTime = ({ type, sort }) => {
    let that = this;
    let year = '';
    let month = '';
    let day = '';
    let dateStr = this.state.currentDate;
    year = dateStr.substring(0, 4);
    month = parseInt(dateStr.substring(5, 7));
    day = parseInt(dateStr.substring(8, 10));
    let daysData = this._createDateData();
    Picker.init({
      pickerTitleText: '装货起止时间',
      // pickerSubTitleText: '超过装货截止时间后货源将自动过期',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [
        that.state.chooseDate,
        that.state.chooseStartHour,
        that.state.chooseEndHour,
      ],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: daysData,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        that.state.chooseDate = pickedValue[0];
        that.state.chooseStartHour = pickedValue[1];
        that.state.chooseEndHour = pickedValue[2];
        // 判断是否跨年,第一个时间是12月份，当前选择时间是1月，则说明跨年
        let yearInt =
          daysData[0][0].startsWith('12') && pickedValue[0].startsWith('01')
            ? year + 1
            : year;
        let yearDay = (`${yearInt}-${pickedValue[0]}`)
          .replace(/月/, '-')
          .replace(/日/, '');
        that.state.supply.assembleTime =
          `${yearDay} ${that._hourChange(pickedValue[1])}`;
        that.state.supply.assembleTimeLater =
          `${yearDay} ${that._hourChange(pickedValue[2])}`;
        console.log(
          `${that.state.supply.assembleTime
          }%%${
            that.state.supply.assembleTimeLater}`,
        );
        // let str = pickedValue[0] + ',' + pickedValue[1] + '-' + pickedValue[2];
        let times = [pickedValue[0], pickedValue[1]];
        // 点击确定
        this.onChangeTime({ type, sort, times });
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
    });
    Picker.show();
  };

  // 小时处理
  _hourChange(hour) {
    if (hour == '00:00') {
      return '00:00:01';
    }
    if (hour == '24:00') {
      return '23:59:59';
    }
    return `${hour}:00`;
  }

  // 获取当前日期  格式如 2018-12-15
  _getCurrentDate() {
    let currDate = new Date();
    let year = currDate.getFullYear();
    let month = (currDate.getMonth() + 1).toString();
    month = month.padStart(2, '0');
    let dateDay = currDate.getDate().toString();
    dateDay = dateDay.padStart(2, '0');
    let time = `${year}-${month}-${dateDay}`;
    return time;
  }

  // 组装日期数据
  _createDateData() {
    let result = [];
    let month = [];
    // 当前起七天时间
    let time = new Date().getTime(); // 当前毫秒数
    // var time = new Date('2020-12-30').getTime()
    let dayMils = 24 * 60 * 60 * 1000; // 一天的毫秒数常量
    month.push(this._getMonthDay(time));
    for (let index = 0; index < 6; index++) {
      time += dayMils;
      month.push(this._getMonthDay(time));
    }
    // result.push(month,this.createHours(), this.createHours());
    result.push(this.createHours(), this.createHours());
    return result;
  }

  // 获取年
  _getYear(mils) {
    let date = new Date(mils);
    return `${date.getFullYear()}年`;
  }

  // 获取月日
  _getMonthDay(mils) {
    let date = new Date(mils);
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month < 10 ? `0${month}` : month;
    day = day < 10 ? `0${day}` : day;
    return `${month}月${day}日`;
  }

  createHours() {
    let hours = [];
    for (let k = 0; k < 24; k++) {
      hours.push(`${(k < 10 ? '0' : '') + k}:00`);
    }
    return hours;
  }

  // 获取缓存内容
  loadSaveInputParams = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const routerParams = state.params || {};
    const { type } = routerParams;
    if (type == 'edit' || type == 'resend') {
      return;
    }
    AsyncStorage.getItem(cache.REALSE_SOURCE)
      .then((dataJson) => {
        if (!dataJson || dataJson.length <= 0) {
          return;
        }
        let data = JSON.parse(dataJson);
        const {
          installAddressList,
          installAddressListMaxNum,
          offAddressList,
          offAddressListMaxNum,
          sourceInfoIsShow,
          sourceInfoType,
          carNeedIsShow,
          sourceRemarkIsShow,
          hopeFreightIsShow,
          sourceContactIsShow,
          supply,
          treeList,
          currentType,
          currentSort,
          needReceipt,
          isAgree,
          isDisabled,
          isWeighing,
        } = data;
        this.setState({
          installAddressList,
          installAddressListMaxNum,
          offAddressList,
          offAddressListMaxNum,
          sourceInfoIsShow,
          sourceInfoType,
          carNeedIsShow,
          sourceRemarkIsShow,
          hopeFreightIsShow,
          sourceContactIsShow,
          supply,
          treeList,
          currentType,
          currentSort,
          needReceipt,
          isAgree,
          isDisabled,
          isWeighing,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  // 存储输入的内容
  saveInputParams = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const routerParams = state.params || {};
    const { type } = routerParams;
    if (type == 'edit' || type == 'resend') {
      return;
    }
    const {
      installAddressList,
      installAddressListMaxNum,
      offAddressList,
      offAddressListMaxNum,
      sourceInfoIsShow,
      sourceInfoType,
      carNeedIsShow,
      sourceRemarkIsShow,
      hopeFreightIsShow,
      sourceContactIsShow,
      supply,
      treeList,
      currentType,
      currentSort,
      needReceipt,
      isAgree,
      isDisabled,
      isWeighing,
    } = this.state;
    const params = {
      installAddressList,
      installAddressListMaxNum,
      offAddressList,
      offAddressListMaxNum,
      sourceInfoIsShow,
      sourceInfoType,
      carNeedIsShow,
      sourceRemarkIsShow,
      hopeFreightIsShow,
      sourceContactIsShow,
      supply,
      treeList,
      currentType,
      currentSort,
      needReceipt,
      isAgree,
      isDisabled,
      isWeighing,
    };
    AsyncStorage.setItem(cache.REALSE_SOURCE, JSON.stringify(params));
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    paddingHorizontal: px2dp(32),
  },
  leftContainer: {
    backgroundColor: 'pink',
    paddingHorizontal: 20
  },
  addressWrap: {
    // width: px2dp(702),
    width: '100%',
    // height: px2dp(542),
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(12),
    marginTop: px2dp(24),
  },

  addressEnd: {
    // borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
    // height: px2dp(180),
    padding: px2dp(32),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  addressEndSec: {
    // borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
    // height: px2dp(180),
    padding: px2dp(32),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  addressTopMark: {
    width: px2dp(40),
    height: px2dp(40),
    backgroundColor: 'green',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(6),
  },
  addressTopInput: {
    flex: 1,
    height: '100%',
    marginLeft: px2dp(32),
  },
  addressText: {
    lineHeight: px2dp(54),
  },
  dotImg: {
    width: px2dp(42),
    height: px2dp(42),
  },
  dot: {
    width: px2dp(16),
    height: px2dp(16),
    marginHorizontal: px2dp(13),
    borderRadius: px2dp(8),
  },
  floorWrap: {
    borderRadius: px2dp(12),
    width: '100%',
    overflow: 'hidden',
    backgroundColor: mainBgColorWhite,
    marginTop: px2dp(24),
    paddingHorizontal: px2dp(30),
  },
  textDir: {
    textAlign: 'left',
    color: fontColorSecDeepGray,
  },
  labelWidth: {
    width: 98,
  },
  receiptItem: {
    backgroundColor: mainBgColorWhite,
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(112),
  },
  receiptItemLabel: {
    width: px2dp(200),
    color: '#686764',
    fontSize: px2dp(28),
  },
  receiptItemRight: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    flex: 1,
    alignItems: 'center',
  },
});
